#-- coding: utf-8 --

#@File : db_mongo.py.py
#@Software : PyCharm
#@Author : Silva
#@Email : for_billy@163.com
#@Time : 2023/10/8 上午12:06

from pymongo import MongoClient
from TLNewsSpider.config import DB_CONFIG

def get_mongodb(
        database: str,
        host: str = 'localhost:27017',
        is_auth: bool = False,
        user: str = '',
        pwd: str = '',
        is_replica: bool = False,
        replica: str = '',
):
    """
    获取 db 实例
    :param database: 数据库
    :param host: 服务器地址
    :param is_auth: 是否验证用户
    :param user: 用户名
    :param pwd: 密码
    :param is_replica:  是否是集群
    :param replica: 集群名称
    :return db:
    """
    if is_replica:
        url = 'mongodb://%s/?replicaSet=%s' % (host, replica)
    else:
        url = host

    client = MongoClient(url, connect=False, maxPoolSize=50)
    connection = client[database]

    if is_auth:
        connection.authenticate(user, pwd)

    return connection


db = get_mongodb(
    database= DB_CONFIG['mongodb']['database'],
    host=DB_CONFIG['mongodb']['host'],
    is_auth=DB_CONFIG['mongodb']['is_auth'],
    user=DB_CONFIG['mongodb']['user'],
    pwd=DB_CONFIG['mongodb']['pwd'],
    is_replica=DB_CONFIG['mongodb']['is_replica'],
    replica=DB_CONFIG['mongodb']['replica'],
)

